package com.zengqingfa.demo.aop;

import com.zengqingfa.demo.annotation.AspectAnnotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/*
 *  @ author  zengqingfa
 *  @ created in    2020/3/29  21:01
 *
 */
@Component
@Aspect
public class AspectAnnotationAop {

    //拦截指定的方法

    @Pointcut("@annotation(com.zengqingfa.demo.annotation.AspectAnnotation)")
    private void annotationPointCut() {
    }


    @Around("annotationPointCut()")
    public Object annotationAround(ProceedingJoinPoint jp) throws Throwable {
        //获取方法
        Method method = ((MethodSignature) jp.getSignature()).getMethod();
        // 获取AspectAnnotation注解
        AspectAnnotation aspectAnnotation = method.getAnnotation(AspectAnnotation.class);
        boolean flag = aspectAnnotation.isStart();
        //执行方法前
        Object returnVal = null;
        try {
            if (flag) {//如果为true，则计算方法的时间
                Long start = System.currentTimeMillis();
                returnVal = jp.proceed();
                //执行方法后
                System.out.println("执行了：" + (System.currentTimeMillis() - start) + "s");

            } else {//否则不计算
                returnVal = jp.proceed();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return returnVal;
    }

}
